import socketserver
import socket
import json
import constantValues as cv
import debugPrinter as dp
import numpy as np
from lslSender import LSLSender
# import threading

PORT = 8081
mLSL = LSLSender('dummy')

class DATAPKG(object):
    """docstring for DATAPKG"""
    def __init__(self, arg):
        super(DATAPKG, self).__init__()
        self.arg = arg
        # self.pkg_arr = None
        self.last_pkn = None

    def new_data_pkg(self,arr):
        # self.pkg_arr = arr
        json_data = json.loads(bytearray(arr))
        if (cv.JSON_RECV_KEY_PACKET_NUM) in json_data.keys():
            pkn = json_data.get(cv.JSON_RECV_KEY_PACKET_NUM)
            if(self.last_pkn is None):
                self.last_pkn = pkn
            d = pkn - self.last_pkn - 1

            # insert zeros # I do not know how to transfer NAN in lsl, so I use 0 
            if(d>0)&(d<20):
                dp.dpt('lost package insert zeros')
                e = np.zeros(shape=(8,), dtype=int)
                # # e[:] = np.nan
                # a = np.zeros(shape=(4,), dtype=int)
                # # a[:] = np.nan
                for i in range(d): #how many packet lost
                    for i in range(10):
                        mLSL.send_eeg(e)
            self.last_pkn = pkn

        if (cv.JSON_RECV_KEY_DATA_EEG) in json_data.keys():
            e = json_data.get(cv.JSON_RECV_KEY_DATA_EEG)
            arr = np.array(e)
            # if arr.size!=80:
            #     dp.dpt('some thing wrong')
            #     dp.dpt(arr.size)
                # return
            for i in range(10):
                mLSL.send_eeg_mii(e[i*8:i*8+8])

mDP = DATAPKG('dummy')

class MyUDPHandler(socketserver.BaseRequestHandler):

    def handle(self):
        arr = self.request[0].strip()
        mDP.new_data_pkg(arr)
        # socket = self.request[1]
        # print("{} wrote:".format(self.client_address[0]))
        # print(arr)

if __name__ == "__main__":
    host_ip = socket.gethostbyname(socket.gethostname())
    dp.dpt(host_ip)
    # HOST, PORT = , 8081

    with socketserver.ThreadingUDPServer((host_ip, PORT), MyUDPHandler) as server:
        server.serve_forever()














